<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class OrderItem extends Model
{
    protected $fillable = [
        'product_id',
        'product_sku_id',
        'amount',
        'price',
        'rating',
        'review',
        'reviewed_at',
        'detail',
    ];

    protected $casts = [
        'detail' => 'json',
    ];

    protected $dates = ['reviewed_at'];

    public $timestamps = false;

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function productSku()
    {
        return $this->belongsTo(ProductSku::class);
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function comment($data, $images)
    {
        // 添加评论列表
        Comment::query()->create([
            'customer_id' => $this->order->customer_id,
            'product_id' => $this->product_id,
            'content' => (string)$data['content'],
            'score' => (int)$data['score'],
            'level' => (int)$data['level'],
            'has_images' => $images ? 1 : 0,
            'detail' => [
                'images' => (array)$images,
                'product' => $this->detail,
            ],
            'order_id' => $data['order_id'],
            'order_item_id' => $data['item_id'],
        ]);

        return $this->update([
            'reviewed_at' => now(),
            'rating' => (int)$data['score'],
            'review' => (string)$data['content'],
        ]);
    }
}
